#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'gtlions'
import os
import chardet


def cdWalker(cdrom, filename):
    export = ""
    for root, dirs, files in os.walk(cdrom):
        print formatCDinfo(root, dirs, files)
        export += formatCDinfo(root, dirs, files)
    open(filename,'wr').truncate()
    open(filename,'w').write(export)
def cdGrep(cdcpath, keyword):
    filelist = os.listdir(os.getcwd())
    for cdc in filelist:
        if ".cdc" in cdc:
            cdcfile = open(cdc,'r')
            for line in cdcfile.readlines():
                if keyword in line:
                    print line
def _smartcode(stream):
    ustring = stream
    codedetect = chardet.detect(ustring)["encoding"]
    print codedetect
    try:
        print ustring
        ustring = unicode(ustring, codedetect)
        print ustring
        return "%s %s%" %("",ustring.encode('utf8'))
    except:
        return u"bad unicode encode try!"

def formatCDinfo(root, dirs, files):
    export ='\n' + root + '\n'
    for d in dirs:
        export += '-d' + root + _smartcode(d) + '\n'
    for f in files:
        export += '-f %s %s \n' % (root,_smartcode(f))
    export += "="*70
    return export
if __name__ == '__main__':
    cdrom = '/Users/gtlions/gtlions/百度云同步盘/sync/01我的文章'
    filename = 'cdc.cdc'

    cdcpath = os.getcwd()
    keyword = 'a'
    cdWalker(cdrom, filename)
    # cdGrep(cdcpath, keyword)
